package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.mybatisplus.basic.BasePojo;
import com.itheima.sfbx.insurance.constant.CoefficentCacheConstant;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.insurance.mapper.CoefficentMapper;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import com.itheima.sfbx.insurance.service.ICoefficentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CoefficentServiceImpl extends ServiceImpl<CoefficentMapper, Coefficent> implements ICoefficentService {
    @Override
    @Cacheable(value = CoefficentCacheConstant.PAGE, key = "#pageNum+'-'+#pageSize+'-'+#coefficentVO.hashCode()")
    public Page<CoefficentVO> findPage(CoefficentVO coefficentVO, int pageNum, int pageSize) {
        try {
            LambdaQueryWrapper<Coefficent> queryWrapper = getQueryWrapper(coefficentVO);
            Page<Coefficent> page = page(new Page<>(pageNum, pageSize), queryWrapper);
            return BeanConv.toPage(page, CoefficentVO.class);
        } catch (Exception e) {
            log.error("分页查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(CoefficentEnum.PAGE_FAIL);
        }
    }

    private static LambdaQueryWrapper<Coefficent> getQueryWrapper(CoefficentVO coefficentVO) {
        LambdaQueryWrapper<Coefficent> queryWrapper = null;
        if (BeanUtil.isNotEmpty(coefficentVO)) {
            queryWrapper = Wrappers.<Coefficent>lambdaQuery()
                    .eq(StrUtil.isNotBlank(coefficentVO.getCoefficentKey()), Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                    .like(StrUtil.isNotBlank(coefficentVO.getCoefficentKeyName()), Coefficent::getCoefficentKeyName, coefficentVO.getCoefficentKeyName())
                    .eq(StrUtil.isNotBlank(coefficentVO.getDataState()), BasePojo::getDataState, coefficentVO.getDataState())
                    .orderByAsc(Coefficent::getSortNo)
                    .orderByDesc(BasePojo::getCreateTime);
        }
        return queryWrapper;
    }

    @Override
    @Cacheable(value = CoefficentCacheConstant.BASIC, key = "#coefficentId")
    public CoefficentVO findById(String coefficentId) {
        return null;
    }

    @Override
    @Caching(evict = {@CacheEvict(value = CoefficentCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.BASIC, key = "#result.id")
    })
    public CoefficentVO save(CoefficentVO coefficentVO) {
        try {
            Coefficent coefficent = BeanConv.toBean(coefficentVO, Coefficent.class);
            boolean flag = save(coefficent);
            if (!flag) {
                throw new RuntimeException("保存失败");
            }
            return BeanConv.toBean(coefficent, CoefficentVO.class);
        } catch (RuntimeException e) {
            log.error("保存异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
    }

    @Override
    @Caching(evict = {@CacheEvict(value = CoefficentCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.BASIC,key = "#coefficentVO.id")
    })
    public Boolean update(CoefficentVO coefficentVO) {
        try {
            Coefficent coefficent = BeanConv.toBean(coefficentVO, Coefficent.class);
            boolean flag = updateById(coefficent);
            if (!flag) {
                throw new RuntimeException("修改失败");
            }
            return flag;
        } catch (RuntimeException e) {
            log.error("修改异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
    }

    @Override
    @Caching(evict = {@CacheEvict(value = CoefficentCacheConstant.PAGE,allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.LIST,allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.BASIC,allEntries = true)
    })
    public Boolean delete(String[] checkedIds) {
        try {
            List<Long> list = Arrays.stream(checkedIds).map(Long::valueOf).collect(Collectors.toList());
            boolean flag = removeByIds(list);
            if (!flag) {
                throw new RuntimeException("删除失败");
            }
            return flag;
        } catch (RuntimeException e) {
            log.error("删除异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }
    }

    @Override
    @Cacheable(value = CoefficentCacheConstant.LIST,key = "#coefficentVO.hashCode()")
    public List<CoefficentVO> findList(CoefficentVO coefficentVO) {
        try {
            LambdaQueryWrapper<Coefficent> queryWrapper = getQueryWrapper(coefficentVO);
            List<Coefficent> list = list(queryWrapper);
            return BeanConv.toBeanList(list, CoefficentVO.class);
        } catch (Exception e) {
            log.error("查询列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(CoefficentEnum.LIST_FAIL);
        }
    }

    @Override
    @Cacheable(value = CoefficentCacheConstant.BASIC,key = "#coefficentKey.hashCode()")
    public CoefficentVO findByCoefficentKey(String coefficentKey) {
        try {
            CoefficentVO coefficentVO = new CoefficentVO();
            coefficentVO.setCoefficentKey(coefficentKey);
            LambdaQueryWrapper<Coefficent> queryWrapper = getQueryWrapper(coefficentVO);
            Coefficent coefficent = getOne(queryWrapper);
            return BeanConv.toBean(coefficent, CoefficentVO.class);
        } catch (Exception e) {
            log.error("查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(CoefficentEnum.FIND_ONE_FAIL);
        }
    }
}
